package org.example.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

@RestController
@RequestMapping("/deepseek")
public class DeepSeekController {

    private static final String API_KEY = "sk-e4d6df61863942ee9ec71d078b01dc89"; // 从环境变量获取密钥
    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 调deepseek的API接口
     * @param question
     * @return
     */
    @PostMapping("/answer")
    public ResponseEntity<String> getAnswer(@RequestBody String question) {

        StringBuilder responseContent = new StringBuilder();

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost("https://api.deepseek.com/chat/completions");

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + API_KEY);

            // 构建 JSON 请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("messages", new Object[] {
                    new HashMap<String, String>() {{
                        put("role", "user");
                        put("content", question);
                    }}
            });
            requestBody.put("stream", true);

            // 使用 Jackson 序列化 JSON
            String jsonInput = mapper.writeValueAsString(requestBody);
            httpPost.setEntity(new StringEntity(jsonInput, StandardCharsets.UTF_8));

            // 发送请求并处理响应
            HttpResponse response = httpClient.execute(httpPost);
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.startsWith("data: ")) {
                        String jsonStr = line.substring(6).trim();
                        if ("[DONE]".equals(jsonStr)) {
                            System.out.println("\nStream completed.");
                            break;
                        }
                        try {
                            JsonNode node = mapper.readTree(jsonStr);
                            if (node.has("choices")) {
                                JsonNode contentNode = node.get("choices").get(0)
                                        .get("delta").get("content");
                                if (!contentNode.isNull()) {
                                    responseContent.append(contentNode.asText());
                                }
                            }
                        } catch (Exception e) {
                            System.err.println("JSON解析失败: " + e.getMessage());
                            return ResponseEntity.internalServerError()
                                    .body("{\"error\": \"JSON解析失败: " + e.getMessage() + "\"}");
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("请求失败: " + e.getMessage());
            return ResponseEntity.internalServerError()
                    .body("{\"error\": \"请求失败: " + e.getMessage() + "\"}");
        }

        return ResponseEntity.ok()
                .body("{\"answer\": \"" + responseContent.toString() + "\"}");
    }

}
